<?php

class BaseuserModule extends BaseModule{
	public function __construct($p){
		//BaseModule::__construct($p);
		if(!file_exists($this->tplpath.'loginform.html'))$this->installtemplates();
	}
	
	private function installtemplates(){
		$path=PATH_FFWD.'defaulttemplates/baseuser/';
		if(!is_dir($this->tplpath))mkdir($this->tplpath,0766,1);
		$dir=opendir($path);
		while($f=readdir($dir)){
			if($f[0]!='.'){
				file_put_contents($this->tplpath.$f,file_get_contents($path.$f));
			}
		}
		closedir($dir);
	}
	
	public function indexAction($p){
		new LT('div[id=user_div]');
		$user=&$GLOBALS['user'];
		if(isset($p['error']) && $p['error'])echo errorspan($p['error']);
		if(!$user->name){	
			include $this->tplpath.'loginform.html';
		}else{
			include $this->tplpath.'loggedin.html';
		}	 
		return 0;
	}	
	
	public function dologinAction($p){
		global $app,$user;	
		$r=$user->dologin($p);
		if($r){
			$this->redirectTo(link_for('index',Array('user_error'=>removeaccents($r))));
		}else{
			$this->redirectLast();
		}
	}
	
	public function loginAction($p){
		$this->indexAction($p);	
	}
	
	public function dologoutAction($p){
		global $user,$app;
		$user->dologout();
		$app->redirectLast();		
	}
	
	public function registerAction($p){
		function error_for($f){
			if(!isset($_GET['error_'.$f]))return;
			echo '<tr><td></td><td>'.errorspan(translate($_GET['error_'.$f])).'</td></tr>';
		}
		include $this->tplpath.'register.html';
	}
	
	public function doregisterAction($p){
		global $app,$user;
		print_var($p,'doregister');
		$err=requireNonNULLIndex('username,password,password2,email',$p);
		if(count($err)){
			$this->redirectTo(link_for('register',$err));			
		};
		
		$err['error_username']=validate_username($p['username']);
		if(!$err['error_username'])unset($err['error_username']);
		
		$err['error_password']=validate_password($p['password'],$p['password2']);
		if(!$err['error_password'])unset($err['error_password']);
		
		$err['error_email']=validate_email($p['email']);
		if(!$err['error_email'])unset($err['error_email']);
		
		
		if(count($err)){
			$app->controller->redirectTo('register',$err);			
		};
		
		
		if($user->register($p)==0){
			$app->controller->redirectTo(link_for('regsuccess',Array('email'=>$p['email'])));
		}else{
			$app->controller->redirectTo(link_for('register',Array('error_name'=>'unexpected_error')));
		}
				
	}
	
	public function regsuccessAction($p){
		include $this->tplpath.'regsuccess.html';		
	}
	




}
